package com.app.asktom;

import java.util.Map;

import com.app.asktom.abs.AbsActivity;
import com.app.asktom.abs.AbsHttpAsync;
import com.app.asktom.component.Config;
import com.app.asktom.component.DeviceHelper;
import com.app.asktom.component.HttpHelper;
import com.app.asktom.component.JsonHelper;
import com.app.asktom.component.RandomGenerator;
import com.app.asktom.model.User;

import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import android.support.v4.app.NavUtils;


public class RegisterActivity extends AbsActivity {

	private RegisterActivity thisActivity;
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.registration);
		thisActivity = this;
		// Show the Up button in the action bar.
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.register, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void register(View view) {
		User user = new User(this);
		String phoneNumber = this.getTextValue(R.id.txtPhoneNumber); 
		Map<String,String> map = user.getUserInfoByPhone(
				phoneNumber);
		
		// check if activation code already in database
		if(map.isEmpty()) {
			RegistrationTask registrationTask = new RegistrationTask();
			registrationTask.setShowLoading(true);
			registrationTask.setActivity(this);
			registrationTask.execute(Config.getInstance().get("baseUrl"));
		
		// send activation code through sms if already in database	
		} else {
			String msg = map.get("activationCode");
			DeviceHelper.sendSms(this, phoneNumber, msg);
		}
		this.hideKeyboard(R.id.txtName);
	}
	
	private class RegistrationTask extends AbsHttpAsync { 
		
		protected String pass;
		
		@Override
		protected void onPostExecute(String result) {
			int start = this.getResponse().indexOf("{");
			Log.d("DEBUG", "start:" + start);
			int end = this.getResponse().length();
			String msg = "failed";
			String sms = "";
			if(this.getResponse().startsWith("error:")) {
				
			} else if(start >= 0) {
				Log.d("DEBUG", "PASOK");
				this.response = this.response.substring(start, end);
				Map<String,String> json = JsonHelper.getInstance()
						.responseRegistration(this.response);
				msg = json.get("msg");
				if(json.get("stat").equals("OK")){
					
					sms = "KEY: " + json.get("akey");
					Log.d("DEBUG", "send sms "+sms);
					DeviceHelper.sendSms(this.activity,
						this.getTextValue(R.id.txtPhoneNumber), sms);
					User user = new User(this.activity);
					user.setName(this.getTextValue(R.id.txtName));
					user.setActivationCode(json.get("akey"));
					user.setPassword(this.pass);
					user.setIsActivated("FALSE");
					user.setPhone(this.getTextValue(
							R.id.txtPhoneNumber));
					user.setIsSendFriend("FALSE");
					user.insertUser();
				}
			}
			Toast.makeText(this.activity, msg,Toast.LENGTH_LONG)
				.show();
			super.onPostExecute(result);
			Intent intent = new Intent(thisActivity, ActivationActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			thisActivity.finish();
		}	
		
		@Override
		protected String doInBackground(String... params) {
			String password = RandomGenerator.generateRandomNumber(5);
			this.pass = password;
			Log.d("DEBUG", "reg pass:" + this.pass);
			HttpHelper httpHelper = new HttpHelper();
			httpHelper.setPost(true);
			httpHelper.setUrl(params[0]);
			httpHelper.setPostParam("appId", "NPAPP");
			httpHelper.setPostParam("req", "REG");
			httpHelper.setPostParam("user", 
					this.getTextValue(R.id.txtPhoneNumber));
			httpHelper.setPostParam("pass", password);
			httpHelper.setPostParam("pass2", password);
			httpHelper.setPostParam("name",
					this.getTextValue(R.id.txtName));
			httpHelper.setPostParam("NPAgrp", "GEN");
			httpHelper.setPostParam("dfmt", "JS");
			httpHelper.setPostParam("gotoApp", "WBTOM");
			httpHelper.setPostParam("gotoReq", "VIEW");
			httpHelper.setPostParam("appkey", "326e1eebc1");	
			httpHelper.sendRequest();
			this.setResponse(httpHelper.getResponse());
			return this.getResponse();
		}
	}
}
